<?php

namespace app\admin\controller\hr;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * HR考勤管理
 */
class Attendance extends Backend
{
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = Db::name('hr_attendance');
    }
    
    /**
     * 查看考勤列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total = $this->model
                ->alias('a')
                ->join('user u', 'a.user_id = u.id', 'LEFT')
                ->where($where)
                ->count();
            
            $list = $this->model
                ->alias('a')
                ->join('user u', 'a.user_id = u.id', 'LEFT')
                ->field('a.*, u.nickname as user_name')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            
            // 格式化数据
            foreach ($list as &$item) {
                $item['clock_in_time_text'] = $item['clock_in_time'] ? date('Y-m-d H:i:s', $item['clock_in_time']) : '';
                $item['clock_out_time_text'] = $item['clock_out_time'] ? date('Y-m-d H:i:s', $item['clock_out_time']) : '';
                $item['status_text'] = $this->getStatusText($item['attendance_status']);
            }
            
            $result = ['total' => $total, 'rows' => $list];
            return json($result);
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 考勤详情
     */
    public function detail($ids = null)
    {
        $row = $this->model
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'LEFT')
            ->field('a.*, u.nickname as user_name, u.mobile')
            ->where('a.id', $ids)
            ->find();
        
        if (!$row) {
            $this->error('记录不存在');
        }
        
        // 格式化数据
        $row['clock_in_time_text'] = $row['clock_in_time'] ? date('Y-m-d H:i:s', $row['clock_in_time']) : '';
        $row['clock_out_time_text'] = $row['clock_out_time'] ? date('Y-m-d H:i:s', $row['clock_out_time']) : '';
        $row['status_text'] = $this->getStatusText($row['attendance_status']);
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    
    /**
     * 月度统计
     */
    public function monthly()
    {
        if ($this->request->isAjax()) {
            // 手动获取参数
            $yearMonth = $this->request->get('year_month', date('Y-m'));
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $sort = $this->request->get('sort', 'id');
            $order = $this->request->get('order', 'desc');
            $offset = $this->request->get('offset', 0);
            
            // 构建查询条件
            $where = [];
            $where['m.year_month'] = $yearMonth;
            
            // 如果有搜索条件
            $filter = $this->request->get('filter', '');
            if ($filter) {
                $filterArr = json_decode($filter, true);
                if ($filterArr && is_array($filterArr)) {
                    foreach ($filterArr as $key => $value) {
                        if ($value !== '') {
                            $where['m.' . $key] = ['like', '%' . $value . '%'];
                        }
                    }
                }
            }
            
            $total = Db::name('hr_attendance_monthly')
                ->alias('m')
                ->join('user u', 'm.user_id = u.id', 'LEFT')
                ->where($where)
                ->count();
            
            $list = Db::name('hr_attendance_monthly')
                ->alias('m')
                ->join('user u', 'm.user_id = u.id', 'LEFT')
                ->field('m.*, u.nickname as user_name')
                ->where($where)
                ->order('m.' . $sort, $order)
                ->limit($offset, $limit)
                ->select();
            
            $result = ['total' => $total, 'rows' => $list];
            return json($result);
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 统计分析
     */
    public function statistics()
    {
        $yearMonth = $this->request->get('year_month', date('Y-m'));
        
        // 获取统计数据
        $stats = [
            'total_employees' => Db::name('user')->where('status', 'normal')->count(),
            'total_attendance' => $this->model->where('attendance_date', 'like', $yearMonth . '%')->count(),
            'normal_count' => $this->model->where('attendance_date', 'like', $yearMonth . '%')->where('attendance_status', 1)->count(),
            'late_count' => $this->model->where('attendance_date', 'like', $yearMonth . '%')->where('is_late', 1)->count(),
            'early_leave_count' => $this->model->where('attendance_date', 'like', $yearMonth . '%')->where('is_early_leave', 1)->count(),
        ];
        
        // 获取每日出勤趋势（最近30天）
        $trendData = [];
        for ($i = 29; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $count = $this->model->where('attendance_date', $date)->count();
            $trendData['dates'][] = $date;
            $trendData['counts'][] = $count;
        }
        
        $this->view->assign('stats', $stats);
        $this->view->assign('trendData', $trendData);
        $this->view->assign('yearMonth', $yearMonth);
        
        return $this->view->fetch();
    }
    
    /**
     * 导出考勤数据
     */
    public function export()
    {
        $yearMonth = $this->request->get('year_month', date('Y-m'));
        
        $list = $this->model
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'LEFT')
            ->field('a.*, u.nickname as user_name, u.mobile')
            ->where('a.attendance_date', 'like', $yearMonth . '%')
            ->order('a.attendance_date desc, a.user_id asc')
            ->select();
        
        // 格式化数据
        foreach ($list as &$item) {
            $item['clock_in_time_text'] = $item['clock_in_time'] ? date('H:i:s', $item['clock_in_time']) : '';
            $item['clock_out_time_text'] = $item['clock_out_time'] ? date('H:i:s', $item['clock_out_time']) : '';
            $item['status_text'] = $this->getStatusText($item['attendance_status']);
        }
        
        $this->exportExcel($list, '考勤记录_' . $yearMonth, [
            '日期' => 'attendance_date',
            '员工姓名' => 'user_name',
            '手机号' => 'mobile',
            '上班时间' => 'clock_in_time_text',
            '上班地点' => 'clock_in_address',
            '下班时间' => 'clock_out_time_text',
            '下班地点' => 'clock_out_address',
            '工作时长' => 'work_hours',
            '状态' => 'status_text',
            '备注' => 'remark'
        ]);
    }
    
    /**
     * 考勤配置
     */
    public function config()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            $config = Db::name('hr_attendance_config')->where('is_default', 1)->find();
            
            $data = [
                'work_start_time' => $params['work_start_time'],
                'work_end_time' => $params['work_end_time'],
                'late_threshold' => $params['late_threshold'],
                'early_leave_threshold' => $params['early_leave_threshold'],
                'clock_in_distance' => $params['clock_in_distance'],
                'office_longitude' => $params['office_longitude'],
                'office_latitude' => $params['office_latitude'],
                'office_address' => $params['office_address'],
                'updatetime' => time()
            ];
            
            if ($config) {
                Db::name('hr_attendance_config')->where('id', $config['id'])->update($data);
            } else {
                $data['config_name'] = '默认配置';
                $data['is_default'] = 1;
                $data['status'] = 1;
                $data['createtime'] = time();
                Db::name('hr_attendance_config')->insert($data);
            }
            
            $this->success('保存成功');
        }
        
        $config = Db::name('hr_attendance_config')->where('is_default', 1)->find();
        
        $this->view->assign('config', $config);
        return $this->view->fetch();
    }
    
    /**
     * 获取状态文本
     */
    private function getStatusText($status)
    {
        $statusMap = [
            1 => '正常',
            2 => '迟到',
            3 => '早退',
            4 => '旷工',
            5 => '请假',
            6 => '加班'
        ];
        return $statusMap[$status] ?? '未知';
    }
    
    /**
     * 导出Excel
     */
    private function exportExcel($data, $filename, $columns)
    {
        vendor('phpexcel.PHPExcel');
        
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        
        // 设置表头
        $col = 'A';
        foreach ($columns as $header => $field) {
            $objPHPExcel->getActiveSheet()->setCellValue($col . '1', $header);
            $col++;
        }
        
        // 填充数据
        $row = 2;
        foreach ($data as $item) {
            $col = 'A';
            foreach ($columns as $field) {
                $value = is_array($field) ? ($item[$field[0]] ?? '') : ($item[$field] ?? '');
                $objPHPExcel->getActiveSheet()->setCellValue($col . $row, $value);
                $col++;
            }
            $row++;
        }
        
        // 输出文件
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}
